package org.jeecg.modules.bim.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.bim.entity.BimPointCloud;
import org.jeecg.modules.bim.mapper.IBimPointCloudMapper;
import org.jeecg.modules.bim.service.IBimPointCloudService;
import org.jeecg.modules.project.entity.ProjectInfo;
import org.jeecg.modules.project.service.IProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class BimPointCloudServiceImpl extends ServiceImpl<IBimPointCloudMapper, BimPointCloud> implements IBimPointCloudService {

    @Autowired
    private IProjectInfoService projectInfoService;

    @Override
    @Transactional
    public BimPointCloud addPointCloud(BimPointCloud bimPointCloud) {
        ProjectInfo projectInfo = projectInfoService.getById(bimPointCloud.getProjectInfoId());
        if (Objects.isNull(projectInfo)) {
            log.error("添加bim点云数据,未查询到对应系统项目信息,projectInfoId=>{}", bimPointCloud.getProjectInfoId());
            throw new JeecgBootException("对应工程不存在!");
        }
        //todo 查询点云名称是否存在
        String pointCloud = bimPointCloud.getPointCloud();
        JSONObject jsonObject = JSONObject.parseObject(pointCloud);
        String base = jsonObject.getString("base");
        JSONObject baseObject = JSONObject.parseObject(base);
        String pointCloudId = baseObject.getString("pointCloudId");
        //查询是否存在与输入数据相同的点云名称
        int pointCloudIdCount = baseMapper.findPointCloudId(pointCloudId);
        if(pointCloudIdCount == 0) {
            bimPointCloud.setProjectId(projectInfo.getProjectId());
            this.save(bimPointCloud);
            return bimPointCloud;
        }
        else{
            throw new JeecgBootException("点云名称已存在!");
        }

    }

    @Override
    public BimPointCloud pointCloudByProjectInfoId(Integer projectInfoId) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(BimPointCloud::getProjectInfoId, projectInfoId)
                .one();
    }

    @Override
    public List<BimPointCloud> pointCloudList(Integer projectInfoId, Long projectId) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(projectInfoId != null, BimPointCloud::getProjectInfoId, projectInfoId)
                .eq(projectId != null, BimPointCloud::getProjectId, projectId)
                .list();
    }
}
